package com.microcity.autocomponent.autoview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.util.AttributeSet;
import android.view.View;

import com.microcity.autocomponent.R;

/**
 * Created by Darksiderl on 2017/1/9.
 */
public class DashLineView extends View{

    private PathEffect dpe = null;
    private float[] arrayOfFloat;
    private int dashLineSpace;
    private int dashLineLength;
    private int dashLineColor;
    private Paint mPaint = null;
    private Path mPath = null;


    public DashLineView(Context context) {
        this(context,null);
    }

    public DashLineView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(R.styleable.DashLineView);
        dashLineColor = typedArray.getColor(R.styleable.DashLineView_dash_linecolor, Color.BLACK);
        dashLineLength = typedArray.getColor(R.styleable.DashLineView_dash_linelength, 10);
        dashLineSpace = typedArray.getColor(R.styleable.DashLineView_dash_linespace, 10);
        typedArray.recycle();

        this.mPaint = new Paint();
        this.mPath = new Path();

        this.mPaint.setStyle(Paint.Style.STROKE);
        this.mPaint.setColor(dashLineColor);
        this.mPaint.setAntiAlias(true);
        this.mPaint.setStrokeWidth(4);
        arrayOfFloat = new float[2];
        arrayOfFloat[0] = px2sp(context,dashLineLength);
        arrayOfFloat[1] = px2sp(context,dashLineSpace);
        this.dpe = new DashPathEffect(arrayOfFloat, 1);

    }


    public static int px2sp(Context context, float pxValue) {
        float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        this.mPath.moveTo(0.0F,0.0F);
        this.mPath.lineTo(getMeasuredWidth(),0.0F);
        this.mPaint.setPathEffect(dpe);
        canvas.drawPath(this.mPath,this.mPaint);
    }

    public void setDashStyle(PathEffect p){
        this.dpe = p;
        invalidate();
    }


}
